<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/11/1
 * Time: 9:38 AM
 */

namespace app\admin\logic;


use app\model\AccountCapitalFlow;
use app\model\ActivityOrderAttach;
use app\model\ActivityOrderRefund;
use app\model\Bill;
use extend\Functions;
use extend\STATUS_CODE;
use Naixiaoxin\ThinkWechat\Facade;
use think\facade\Env;

class ActivityOrder
{
    /**
     * @purpose 根据团期ID获取订单信息
     * @param int $group_stage_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function orderByGroupStage (int $group_stage_id): array
    {
        $order      = new \app\model\ActivityOrder();
        $list       = $order
            ->with(['attach' => function($query) {
                $query
                    ->alias('aoa')
                    ->join('activity_collection_point acp', 'aoa.collection_point_id=acp.id')
                    ->field('aoa.id,aoa.order_id,aoa.group_stage_id,aoa.collection_point_id,aoa.fullname,
                    aoa.travel_type,aoa.travel_sex,aoa.travel_mobile,aoa.travel_certificate_type,
                    aoa.travel_certificate_number,aoa.price,aoa.status,aoa.cancel_reason,acp.title,acp.address');
            }, 'member' => function($query) {
                $query->field('uid,nickname,username,mobile');
            }])
            ->where([
                ['group_stage_id', '=', $group_stage_id],
                ['status', 'in', [3,5,99]]
            ])
            ->field('id,uid,activity_id,status,order_no,group_stage_id,pay_money,pay_voucher,
            FROM_UNIXTIME(pay_time, "%Y-%m-%d %H:%i:%s") as sign_up_date,pay_time,pay_no,pay_method')
            ->order('status desc,pay_time desc')
            ->select();
        return Functions::result($list);
    }
    /**
     * @purpose 取消已支付订单
     * @param string $order_no
     * @param string $reason
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public static function cancelByPay(string $order_no, string $reason): array
    {
        $order        = new \app\model\ActivityOrder();
        $order_attach = new ActivityOrderAttach();
        $order_refund = new ActivityOrderRefund();
        $member = new \app\model\Member();
        $order->startTrans();
        $order_info = $order
            ->lock(true)
            ->where('order_no', $order_no)
            ->field('id,pay_money,pay_no,pay_voucher,order_no,pay_method,status,activity_id,group_stage_id,uid')
            ->find();
        if (!$order_info) {
            $order->rollback();
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '订单不存在...!'
            );
        }
        if ($order_info->status !== 99) {
            $order->rollback();
            return Functions::result(
                STATUS_CODE::ORDER_STATUS_ERROR,
                '当前状态不可取消并退款'
            );
        }
        $refund_money     = $order_attach
            ->lock(true)
            ->where([
                'order_id' => $order_info->id,
                'status'   => 99,
            ])
            ->sum('price');
        $order_attach_ids = $order_attach
            ->isUpdate(false)
            ->where([
                'order_id' => $order_info->id,
                'status'   => 99,
            ])
            ->field('id')
            ->select();

        $_order_attach_ids = [];
        array_map(function ($item) use (&$_order_attach_ids) {
            array_push($_order_attach_ids, $item['id']);
        }, $order_attach_ids->toArray());

        $order_attach_result = $order_attach
            ->isUpdate(true)
            ->save(['status' => 4, 'cancel_reason' => $reason], [
                'order_id' => $order_info->id,
                'status'   => 99,
            ]);
        // 构建订单退款数据
        $order_refund_data                    = [];
        $order_refund_data['order_id']        = $order_info->id;
        $order_refund_data['order_attach_id'] = implode(',', $_order_attach_ids);
        $order_refund_data['activity_id']     = $order_info->activity_id;
        $order_refund_data['group_stage_id']  = $order_info->group_stage_id;
        $order_refund_data['order_no']        = $order_info->order_no;
        $order_refund_data['refund_reason']   = $reason;
        $order_refund_data['refund_money']    = $refund_money;
        $order_refund_data['pay_no']          = $order_info->pay_no;
        $order_refund_data['pay_voucher']     = $order_info->pay_voucher;
        $order_refund_data['pay_method']      = $order_info->pay_method;
        $order_refund_data['pay_money']       = $order_info->pay_money;
        $order_refund_data['refund_no']       = date('YmdHis') . Functions::random(18);
        RE_REFUND_NO:
        $order_refund_data['refund_no'] = date('YmdHis') . Functions::random(18);
        if ($order_refund->where('refund_no', $order_refund_data['refund_no'])->count(1) > 0) {
            goto RE_REFUND_NO;
        }
        $order_refund_data['status'] = 1;
        $order_refund_data['uid']    = $order_info->uid;
        $order_refund_result = $order_refund
            ->isUpdate(false)
            ->data($order_refund_data)
            ->save();
        $refund_id           = $order_refund->id;
        $refund = [];
        $refund['refund_id'] = '';
        $member_result = true;
        switch ($order_refund_data['pay_method']) {
            case 1: // 微信公众号支付
                $refund              = self::wechatOfficialAccountRefund(
                    $order_refund_data['pay_no'],
                    $order_refund_data['refund_no'],
                    $order_refund_data['pay_money'],
                    $order_refund_data['refund_money'],
                    $order_refund_data['refund_reason']
                );
                break;
            case 2: // 微信小程序支付
                break;
            case 3: // 支付宝支付
                $refund     = self::alipayRefund(
                    $order_refund_data['order_no'],
                    $order_refund_data['pay_no'],
                    $order_refund_data['refund_money'] / 100,
                    $order_refund_data['refund_reason'],
                    $order_refund_data['refund_no']
                );
                break;
            case 10: // 余额支付
                $member_result = $member
                    ->where('uid', $order_refund_data['uid'])
                    ->setInc('balance', $order_refund_data['refund_money']);
                AccountCapitalFlow::M()
                    ->data([
                        'uid'          => $order_refund_data['uid'],
                        'quota'        => $order_refund_data['refund_money'],
                        'type'         => 1,
                        'descriptions' => '退款原因【'.$order_refund_data['refund_reason'].'】',
                    ])
                    ->save();
                break;
        }
        $status = 5;
        if (in_array($order_refund_data['pay_method'], [3,10])) {
            $status = 3;
        }
        $refund_result       = $order_attach
            ->isUpdate(true)
            ->save(['status' => $status], ['id' =>  $_order_attach_ids]);
        $status = 2;
        if (in_array($order_refund_data['pay_method'], [3,10])) {
            $status = 3;
        }
        $refund_order_result = $order_refund
            ->isUpdate(true)
            ->save(
                [
                    'status'         => $status,
                    'transaction_id' => $refund['refund_id'],
                ],
                ['id' => $refund_id]
            );


        $status = 5;
        if (in_array($order_refund_data['pay_method'], [3,10])) {
            $status = 3;
        }
        $order_result   = $order
            ->isUpdate(true)
            ->save(['status' => $status],['id' => $order_info->id]);
        if ($order_refund_result &&
            $order_attach_result &&
            $order_result &&
            $refund_result &&
            $member_result &&
            $refund_order_result) {
            $order_attach->commit();
            return Functions::result();
        }
        $order_attach->rollback();
        return Functions::result(
            STATUS_CODE::FAIL,
            '取消失败'
        );
    }

    /**
     * @purpose 取消出行人（支付之后）
     * @param int $attach_id
     * @param string $reason
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public static function cancelTravelByPay(
        int $attach_id,
        string $reason): array
    {
        $order_attach = new ActivityOrderAttach();
        $order_refund = new ActivityOrderRefund();
        $order        = new \app\model\ActivityOrder();
        $member        = new \app\model\Member();
        $order_attach->startTrans();
        $order_attach_info = $order_attach
            ->lock(true)
            ->alias('aoa')
            ->join('activity_order ao', 'ao.id=aoa.order_id')
            ->join('activity a', 'aoa.activity_id=a.id')
            ->where('aoa.id', $attach_id)
            ->field('aoa.id,aoa.order_id,ao.pay_money,ao.pay_no,ao.pay_voucher,ao.pay_method,aoa.price,
            aoa.activity_id,aoa.group_stage_id,aoa.status,aoa.group_stage_id,ao.uid,ao.order_no,a.title as activity_title')
            ->find();
        if ($order_attach_info->status !== 99) {
            $order_attach->rollback();
            return Functions::result(
                STATUS_CODE::FAIL,
                '当前状态不可取消'
            );
        }
        // 修改出行人状态
        $order_attach_result = $order_attach
            ->isUpdate(true)
            ->save(
                ['status' => 4, 'cancel_reason' => $reason],
                ['id' => $attach_id]
            );
        // 构建订单退款数据
        $order_refund_data                    = [];
        $order_refund_data['order_id']        = $order_attach_info->order_id;
        $order_refund_data['order_attach_id'] = $attach_id;
        $order_refund_data['activity_id']     = $order_attach_info->activity_id;
        $order_refund_data['group_stage_id']  = $order_attach_info->group_stage_id;
        $order_refund_data['order_no']        = $order_attach_info->order_no;
        $order_refund_data['refund_reason']   = $reason;
        $order_refund_data['refund_money']    = $order_attach_info->price;
        $order_refund_data['pay_no']          = $order_attach_info->pay_no;
        $order_refund_data['pay_voucher']     = $order_attach_info->pay_voucher;
        $order_refund_data['pay_method']      = $order_attach_info->pay_method;
        $order_refund_data['pay_money']       = $order_attach_info->pay_money;
        $order_refund_data['refund_no']       = date('YmdHis') . Functions::random(18);
        RE_REFUND_NO:
        $order_refund_data['refund_no'] = date('YmdHis') . Functions::random(18);
        if ($order_refund->where('refund_no', $order_refund_data['refund_no'])->count(1) > 0) {
            goto RE_REFUND_NO;
        }
        $order_refund_data['status'] = 1;
        $order_refund_data['uid']    = $order_attach_info->uid;

        $order_refund_result = $order_refund
            ->isUpdate(false)
            ->data($order_refund_data)
            ->save();
        $refund_id           = $order_refund->id;
        $refund = [];
        $member_result = true;
        $refund['refund_id'] = '';
        switch ($order_attach_info['pay_method']) {
            case 1: // 微信公众号支付
                $refund              = self::wechatOfficialAccountRefund(
                    $order_refund_data['pay_no'],
                    $order_refund_data['refund_no'],
                    $order_refund_data['pay_money'],
                    $order_refund_data['refund_money'],
                    $order_refund_data['refund_reason']
                );
                break;
            case 2: // 微信小程序支付
                break;
            case 3: // 支付宝支付
                $refund     = self::alipayRefund(
                    $order_refund_data['order_no'],
                    $order_refund_data['pay_no'],
                    $order_refund_data['refund_money'] / 100,
                    $order_refund_data['refund_reason'],
                    $order_refund_data['refund_no']
                );
                break;
            case 10: // 余额支付
                $member_result = $member
                    ->where('uid', $order_refund_data['uid'])
                    ->setInc('balance', $order_refund_data['refund_money']);
                AccountCapitalFlow::M()
                    ->data([
                        'uid'          => $order_refund_data['uid'],
                        'quota'        => $order_refund_data['refund_money'],
                        'type'         => 1,
                        'descriptions' => '退款原因【'.$order_refund_data['refund_reason'].'】',
                    ])
                    ->save();
                break;
        }
        $status = 5;
        if (in_array($order_refund_data['pay_method'], [3,10])) {
            $status = 3;
        }
        $refund_result       = $order_attach
            ->isUpdate(true)
            ->save(['status' => $status], ['id' => $attach_id]);
        $status = 2;
        if (in_array($order_refund_data['pay_method'], [3,10])) {
            $status = 3;
        }
        $refund_order_result = $order_refund
            ->isUpdate(true)
            ->save(
                [
                    'status'         => $status,
                    'transaction_id' => $refund['refund_id'],
                ],
                ['id' => $refund_id]
            );
        // 如果是支付宝则记录到账单
        if (in_array($order_refund_data['pay_method'], [3,10])) {

            // 记录账单活动支付账单
            Bill::addToBill(
                $order_attach_info->uid,
                2,
                $order_refund_data['refund_no'],
                $order_refund_data['refund_money'],
                0,
                '活动退款: 【'.$order_attach_info->activity_title.'】,退款原因【'.$reason.'】'
            );
        }
        // 检测当前订单是否全部申请退款
        $order_result = true;
        if ($order_attach->where([
                'status' => 99,
                'order_id' => $order_attach_info->order_id
            ])->count(1) < 1) {

            $status = 5;
            if (in_array($order_refund_data['pay_method'], [3,10])) {
                $status = 3;
            }
            $order_result = $order
                ->isUpdate(true)
                ->save(['status' => $status], ['id' => $order_attach_info->order_id]);
        }
        if ($order_refund_result &&
            $order_attach_result &&
            $order_result &&
            $refund_result &&
            $member_result &&
            $refund_order_result) {
            $order_attach->commit();
            return Functions::result();
        }
        $order_attach->rollback();
        return Functions::result(
            STATUS_CODE::FAIL,
            '取消失败'
        );
    }

    /**
     * @purpose 微信公众号退款
     * @param $transaction_id 微信支付单号
     * @param $refund_no 退款单号
     * @param $total_money 订单总金额
     * @param $refund_money 退款金额
     * @param string $total_money 退款原因
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    private static function wechatOfficialAccountRefund(
        $pay_no,
        $refund_no,
        $total_money,
        $refund_money,
        $reason = '')
    {
        $app    = Facade::payment('official_account');
        $result = $app->refund->byTransactionId(
            $pay_no,
            $refund_no,
            $total_money,
            $refund_money,
            [
                'refund_desc' => $reason,
                'notify_url'  => config('wechat.payment.official_account.refund_notify_url'),
            ]
        );
        // 申请退款成功
        if (isset($result['result_code']) && $result['result_code'] === 'SUCCESS') {
            return $result;
        }
        if (isset($result['err_code_des'])) {
            exception($result['err_code_des']);
        }
        exception($result['return_msg']);

    }


    /**
     * @purpose 支付宝退款
     * @param $out_trade_no // 订单支付时传入的商户订单号,不能和 trade_no同时为空。
     * @param $trade_no // 支付宝交易号，和商户订单号不能同时为空
     * @param $refund_amount // 需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
     * @param $refund_reason // 退款的原因说明
     * @param $out_request_no // 标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传。
     * @throws \Exception
     */
    private static function alipayRefund (
        $out_trade_no,
        $trade_no,
        $refund_amount,
        $refund_reason,
        $out_request_no) {
        include Env::get('root_path'). 'extend/alipay/AopSdk.php';
        include Env::get('root_path'). 'extend/alipay/aop/request/AlipayTradeRefundRequest.php';
        $aop = new \AopClient();
        $aop->gatewayUrl                = 'https://openapi.alipay.com/gateway.do';
        $aop->appId                     = config('alipay.app.appid');
        $aop->rsaPrivateKey             = config('alipay.app.private_key');
        $aop->format                    = "json";
        $aop->charset                   = "UTF-8";
        $aop->signType                  = "RSA";
        $aop->apiVersion                = '1.0';
        $aop->alipayrsaPublicKey        = config('alipay.app.public_key');
        $content = [];
        $content['out_trade_no']        = $out_trade_no;
        $content['trade_no']            = $trade_no;
        $content['refund_amount']       = $refund_amount;
        $content['refund_reason']       = $refund_reason;
        $content['out_request_no']      = $out_request_no;
        $request = new \AlipayTradeRefundRequest();
        $request->setBizContent(json_encode($content));
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        if ((int) $result->$responseNode->code !== 10000) {
            exception($result->$responseNode->msg);
        }
        return ['refund_id' => $result->$responseNode->trade_no];
    }
    /**
     * @purpose 订单未支付时取消出行人
     * @param int $attach_id
     * @param string $reason
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function cancelTravelByNotPay(
        int $attach_id,
        string $reason = ''
    ): array
    {
        $order        = new \app\model\ActivityOrder();
        $order_attach = new ActivityOrderAttach();
        $order->startTrans();
        $order_attach_info = $order_attach
            ->lock(true)
            ->where('id', $attach_id)
            ->field('id,order_id,status')
            ->find();
        if ($order_attach_info->status !== 1) {
            return Functions::result(
                STATUS_CODE::FAIL,
                '该状态不可取消'
            );
        }
        $order_attach_result = $order_attach
            ->isUpdate(true)
            ->save(
                ['status' => 2, 'cancel_reason' => $reason],
                ['id' => $attach_id]
            );
        $order_result        = true;
        if ($order_attach->where([
                'order_id' => $order_attach_info->order_id,
                'status'   => 1,
            ])->count(1) < 1) {
            $order_result = $order
                ->isUpdate(true)
                ->save(
                    ['status' => 4],
                    ['id' => $order_attach_info->order_id]);
        }
        if ($order_result && $order_attach_result) {
            $order->commit();
            return Functions::result();
        }
        $order->rollback();
        return Functions::result(
            STATUS_CODE::FAIL,
            '取消失败'
        );
    }

    /**
     * @purpose 未支付时取消订单
     * @param string $order_no
     * @param string $reason
     * @param int $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function cancelByNotPay(
        string $order_no = '',
        string $reason = ''): array
    {
        if (!$order_no) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误...!'
            );
        }
        $order        = new \app\model\ActivityOrder();
        $order_attach = new ActivityOrderAttach();
        $order->startTrans();
        $order_info = $order
            ->lock(true)
            ->where(['order_no' => $order_no])
            ->field('id,uid,activity_id,status,order_no,pay_money')
            ->find();
        if (!$order_info) {
            $order->rollback();
            return Functions::result(
                STATUS_CODE::FAIL,
                '订单不存在...!'
            );
        }
        if ($order_info->status !== 1) {
            $order->rollback();
            return Functions::result(
                STATUS_CODE::ORDER_STATUS_ERROR,
                '订单状态错误...!'
            );
        }
        $order_result        = $order
            ->isUpdate(true)
            ->save(
                ['status' => 4],
                ['id' => $order_info->id]);
        $order_attach_result = $order_attach
            ->isUpdate(true)
            ->save(
                ['status' => 2, 'cancel_reason' => $reason],
                ['order_id' => $order_info->id]);
        if ($order_result && $order_attach_result) {
            $order->commit();
            return Functions::result();
        }
        $order->rollback();
        return Functions::result(
            STATUS_CODE::UPDATE_FAIL,
            '取消失败'
        );
    }

    /**
     * @purpose 编辑出行人
     * @param array $attach
     * @return array
     */
    public static function editAttach(array $attach): array
    {
        $model = new ActivityOrderAttach();
        if (isset($attach['price'])) {
            unset($attach['price']);
        }
        $result = $model
            ->isUpdate(true)
            ->allowField(true)
            ->save($attach, ['id' => $attach['id']]);
        if ($result) {
            return Functions::result();
        }
        return Functions::result(
            STATUS_CODE::UPDATE_FAIL,
            '编辑失败'
        );
    }

    /**
     * @purpose 获取订单详情
     * @param string $order_no
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function detail(string $order_no = ''): array
    {
        if (!$order_no) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误'
            );
        }
        $model  = new \app\model\ActivityOrder();
        $result = $model
            ->alias('ao')
            ->with(['attach' => function ($query) {
                $query
                    ->alias('aoa')
                    ->join('activity_collection_point acp', 'acp.id=aoa.collection_point_id')
                    ->field('aoa.id,aoa.order_id,aoa.collection_point_id,aoa.fullname,aoa.travel_type,aoa.travel_sex,
                    aoa.travel_mobile,
                    aoa.travel_certificate_type,aoa.travel_certificate_number,aoa.price,aoa.status,aoa.cancel_reason,
                    acp.address,acp.title');
            }, 'activity'    => function ($query) {
                $query
                    ->alias('a')
                    ->join('club c', 'a.club_id=c.uid')
                    ->field('a.id,a.title,a.thumb,c.name as club_name,a.city_name,a.county_name');
            }, 'groupStage'  => function ($query) {
                $query
                    ->field('id,
                    FROM_UNIXTIME(start_time, "%Y-%m-%d") as start_date,
                    FROM_UNIXTIME(start_time, "%Y%m%d") as stage_num,
                    FROM_UNIXTIME(end_time, "%Y-%m-%d") as end_date,
                    FROM_UNIXTIME(apply_end_date, "%Y-%m-%d") as apply_end_date,adult_price,kid_price,insurance_type,
                    insurance_price,status');
            }, 'member'      => function ($query) {
                $query
                    ->field('uid,username,nickname,avatar,mobile');
            }])
            ->where('ao.order_no', $order_no)
            ->field('ao.id,ao.uid,ao.activity_id,ao.status,ao.pay_method,ao.order_no,ao.group_stage_id,ao.pay_money,ao.pay_time,ao.pay_no,
            (select sum(`price`) from activity_order_attach where (`status` = 1 or `status` = 99) and `order_id`=`ao`.`id`) as total_price,
            FROM_UNIXTIME(ao.create_at, "%Y-%m-%d %H:%i:%s") as create_date,
            FROM_UNIXTIME(ao.pay_time, "%Y-%m-%d %H:%i:%s") as pay_date')
            ->find();
        return Functions::result($result);
    }

    /**
     * @purpose 订单列表
     * @param int $status
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function items(int $status = 1, int $page = 1, int $size = 20): array
    {
        $model   = new \app\model\ActivityOrder();
        $where   = [];
        $where[] = ['status', '=', $status];
        $total   = $model
            ->where($where)
            ->count(1);
        $list    = $model
            ->with(['attach' => function ($query) {
                $query
                    ->alias('aoa')
                    ->join('activity_collection_point acp', 'acp.id=aoa.collection_point_id')
                    ->field('aoa.id,aoa.order_id,aoa.collection_point_id,aoa.fullname,aoa.travel_type,aoa.travel_sex,aoa.travel_mobile,
                    aoa.travel_certificate_type,aoa.travel_certificate_number,aoa.price,aoa.status,aoa.cancel_reason,
                    acp.address,acp.title');
            }, 'activity'    => function ($query) {
                $query
                    ->alias('a')
                    ->join('club c', 'a.club_id=c.uid')
                    ->field('a.id,a.title,a.thumb,c.name as club_name,a.city_name,a.county_name');
            }, 'groupStage'  => function ($query) {
                $query
                    ->field('id,
                    FROM_UNIXTIME(start_time, "%Y-%m-%d") as start_date,
                    FROM_UNIXTIME(start_time, "%Y%m%d") as stage_num,
                    FROM_UNIXTIME(end_time, "%Y-%m-%d") as end_date,
                    FROM_UNIXTIME(apply_end_date, "%Y-%m-%d") as apply_end_date,adult_price,kid_price,insurance_type,insurance_price,status');
            }, 'member'      => function ($query) {
                $query
                    ->field('uid,username,nickname,avatar,mobile');
            }])
            ->where($where)
            ->field('id,uid,activity_id,status,order_no,group_stage_id,pay_method,pay_money,pay_time,pay_no,
            FROM_UNIXTIME(create_at, "%Y-%m-%d %H:%i:%s") as create_date,
            FROM_UNIXTIME(pay_time, "%Y-%m-%d %H:%i:%s") as pay_date')
            ->page($page, $size)
            ->order('pay_time desc,create_at desc')
            ->select();
        return Functions::result([
            'total' => $total,
            'list'  => $list,
        ]);
    }
}